package com.springboot.java.design.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @Author: TongRui乀
 * @Date: 2020-07-01 10:16
 * @description： 测试动态代理  Java 提供的Proxy
 */
public class TestProxy {

    public static void main(String[] args) {
        GrateWallCar car = new GrateWallCar();

        // 获取代理类
        JDKProxy jdkProxy = new JDKProxy(car);

        // 生成代理对象
        Car proxyCar = (Car) Proxy.newProxyInstance(car.getClass().getClassLoader(), car.getClass().getInterfaces(), jdkProxy);

        proxyCar.run();
    }

}


interface Car{
    void run();
}

class GrateWallCar implements Car{

    @Override
    public void run() {
        System.out.println("the grate wall car is running");
    }
}

/**
 *  代理类
 */
class JDKProxy implements InvocationHandler{

    private Object target;

    JDKProxy(Object target){
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        System.out.println("代理汽车工厂");

        return method.invoke(target, args);
    }

}